// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.api.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class FileUtil {
	
	public static String getContents(File aFile) throws FileNotFoundException, IOException {
		//...checks on aFile are elided
		StringBuffer contents = new StringBuffer();
		
		//declared here only to make visible to finally clause
		BufferedReader input = null;
		//use buffering, reading one line at a time
		//FileReader always assumes default encoding is OK!
		input = new BufferedReader( new FileReader(aFile) );
		String line = null; //not declared within while loop
		/*
		* readLine is a bit quirky :
		* it returns the content of a line MINUS the newline.
		* it returns null only for the END of the stream.
		* it returns an empty String if two newlines appear in a row.
		*/
		while (( line = input.readLine()) != null){
			contents.append(line);
			contents.append(System.getProperty("line.separator"));
		}

		if (input!= null) {
			//flush and close both "input" and its underlying FileReader
			input.close();
		}
	    
		return contents.toString();
	}
	
	public static void appendContents(File file, String content) throws UtilityException {
		writeContents(file, content, true);
	}
	
	public static void setContents(File file, String content) throws UtilityException {
		writeContents(file, content, false);
	}
	
	private static void writeContents(File file, String content, boolean append) throws UtilityException {
		try {
			if(!file.exists()){
				if(!file.createNewFile()){
					throw new IOException("The file " + file.getAbsolutePath() + " cannot be created");
				}
			}
			
			Writer output = new BufferedWriter( new FileWriter(file, append) );
			
			output.write(content);
			output.close();
		} catch (IOException e) {
			throw new UtilityException("IOException caugth", e);
		}
	}

}
